package com.example.larouzey.recyclerview_201ljy;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * Created by Larouzey on 2017/4/12.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context context;
    private LayoutInflater layoutInflater;//动态加载布局
    private List<ArticleBean> list;

    public MyAdapter(Context context) {
        this.context=context;
        layoutInflater=LayoutInflater.from(this.context);
    }

    //传递数据源
    public void setList(List<ArticleBean> list){
        this.list=list;
    }

    //定义ViewHolder子类
    public class ViewHolder extends RecyclerView.ViewHolder{
        ImageView imv;
        TextView tv,tv1,tv2;
        Button bt;

        public ViewHolder(View itemView) {
            super(itemView);
            imv=(ImageView)itemView.findViewById(R.id.imageView);
            tv=(TextView)itemView.findViewById(R.id.textView);
            tv1=(TextView)itemView.findViewById(R.id.textView2);
            tv2=(TextView)itemView.findViewById(R.id.textView3);
            bt=(Button)itemView.findViewById(R.id.button);
        }
    }

    //为了每个Item生成对应的View
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {
        ArticleBean articleBean=list.get(position);
        if(articleBean==null){
            return ;
        }
        holder.imv.setImageResource(articleBean.getImgid());
        holder.tv.setText(articleBean.getTitle());
        holder.tv1.setText(articleBean.getDescription());
        holder.tv2.setText(articleBean.getTime());

        holder.bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);
                notifyDataSetChanged();
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                int id=list.get(position).getArticleId();
                Toast.makeText(context,""+id,Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
